import zmail
import sys
import configparser
import os
import time

def get_bin_name():
    flist = os.listdir('.')
    for ele in flist:
        if '.bin' in ele:
            target_bin = ele
    # first_file_pure_name = os.path.splitext(target_bin)[0]
    return target_bin

def timestamp():
    stamp = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    return stamp

def send_smoke1_mail(to_list,pdm_times,pcm_times,writecycle_times,smoothover_times,duration_time,evb_mark,test_node,bin_name):
    
    with open('/home/pi/jks_space/backup/smoke1_template.html','r',encoding='utf-8') as f:
        content_html = f.read()

    # ======= NEW information =================
    bin_name = bin_name
    evb_mark = evb_mark
    end_time = timestamp()
    time_cost = duration_time
    test_node = test_node

    config = configparser.ConfigParser()
    config.sections()
    config.read('bin.ini')
    config.sections()

    # get information from ini file
    start_time = config['DEFAULT']['start_time']
    build_time = config['DEFAULT']['build_time']
    build_tag = config['DEFAULT']['build_tag']
    build_url = config['DEFAULT']['build_url']
    trunk_revision = config['DEFAULT']['model_svn_revision']
    build_project = config['DEFAULT']['build_project']
    build_lsp = config['DEFAULT']['build_lsp']
    dsp_freq = config['DEFAULT']['dsp_freq']
    aie_freq = config['DEFAULT']['aie_freq']
    vad_func = config['DEFAULT']['vad']

    html_final = content_html % (build_time,build_tag,build_url,bin_name,trunk_revision,build_project,build_lsp,dsp_freq,aie_freq,vad_func,start_time,end_time,time_cost,evb_mark,bin_name,test_node,pdm_times,pcm_times,writecycle_times,smoothover_times)

    mail = {
        'subject': '[TX210-SMOKE] 1.串口打印测试',  # Anything you want.
        'content_html': html_final, 
        'attachments': '',  # Absolute path will be better.
    }

    server = zmail.server('ceshi@tsingmicro.com', '8nFtMN7eG9xj352y')
    to_list = to_list.split(',')
    server.send_mail(to_list, mail)

def get_error_num():
    ''' 一次性检查4种异常打印出现的次数
    '''
    with open('ser_evb.log','r',encoding='gb2312') as f:
        content_log = f.read()
        
    # print(content_log)
    
    err1_number = content_log.count('error1')
    err2_number = content_log.count('error2')
    err3_number = content_log.count('error3')
    err4_number = content_log.count('error4')
    
    return (err1_number,err2_number,err3_number,err4_number)
    
def main():
    duration_time = sys.argv[1] # cost time
    tomail_list = sys.argv[2]
    evb_mark = sys.argv[3]
    test_node = sys.argv[4]

    bin_name = get_bin_name()
    print([tomail_list])

    pdm_times,pcm_times,writecycle_times,smoothover_times = get_error_num()
    send_smoke1_mail(tomail_list,pdm_times,pcm_times,writecycle_times,smoothover_times,duration_time,evb_mark,test_node,bin_name)

main()